#!/usr/bin/python
# -*- coding: UTF-8 -*-
import gzip
import json
import traceback
from datetime import datetime, timedelta

format_string = "%Y-%m-%d"
date_params = '2024-03-01基础,2024-03-02布局'
count_dict = {'IRP_MONITOR': {}, 'VOS': {}, 'SHOP': {}, 'PEX': {}, 'LIRP': {}, 'IRP': {}, 'ETS': {}, 'BAP': {}}
app_names = [k for k in count_dict]


def get_date_strings():
    # 初始化一个日期列表来存储这段时间内的所有日期字符串
    date_strings = []

    if not date_params:
        # date_params不为None或者”“, 如果为空默认设置为昨天的日期
        start_date = end_date = timedelta(days=-1) + datetime.now()
    else:
        # 字符串为空或为空字符串
        (start_date_str, end_date_str) = date_params.split(',')
        start_date = datetime.strptime(start_date_str, format_string)
        end_date = datetime.strptime(end_date_str, format_string)

    item_date = start_date
    while item_date <= end_date:
        # 将日期对象转换为字符串格式，例如 "YYYY-MM-DD"
        date_string = item_date.strftime("%Y-%m-%d")
        date_strings.append(date_string)
        # 增加一天
        item_date += timedelta(days=1)
    return date_strings


'''
prPath = '/opt/app/billinglog/scmp-provider/billing_s.{date_str}.log.gz'
localPath = './{date_str}.log.gz'
'''


def read_log(date_str):
    try:
        with gzip.open(f'./{date_str}.log.gz', 'rt') as f:
            for line in f:
                pojoStr = line.rsplit('|', maxsplit=1)[1]
                pojo = json.loads(pojoStr)
                app_name = pojo['rsys']
                timestamp = pojo['start']
                apicode = pojo['apicode']
                # python支持秒级精度，需要转换为秒
                timestamp = timestamp / 1000
                dt_object = datetime.fromtimestamp(timestamp)
                log_date_str = dt_object.strftime(format_string)
                if app_name in app_names and pojo['flag'] == 'T':
                    date_apicode_count_dict = count_dict.get(app_name, {})
                    count = date_apicode_count_dict.get(log_date_str + ":" + apicode, 0)
                    date_apicode_count_dict[log_date_str + ":" + apicode] = count + 1
    except FileNotFoundError as err:
        # 获取异常堆栈信息
        exc_info = traceback.format_exc()
        # 添加堆栈信息到异常信息中
        error_message = f"An error occurred: {err}. Stack trace: {exc_info}"
        print(error_message)


if __name__ == '__main__':
    try:
        # 01基础.日期范围解析
        date_strs = get_date_strings()

        # 02布局.按日读取每一个文件
        for date_str in date_strs:
            read_log(date_str)

        # 3.统计appName的调用次数
        count_total_dict = {}
        for k, v in count_dict.items():
            apicode_count_dict = count_dict.get(k)
            total_count = sum(apicode_count_dict.values())
            count_total_dict[k] = total_count

        # 4.打印结果
        print('total print  >>>>>> ', count_total_dict)
        print("detail print >>>>>> ")
        for k, v in count_dict.items():
            for k1, v1 in v.items():
                print(k, k1, v1)
    except Exception as err:
        exc_info = traceback.format_exc()
        # 添加堆栈信息到异常信息中
        error_message = f"An error occurred: {err}. Stack trace: {exc_info}"
        print(error_message)

